/**
 * 
 */
package pt.mleiria.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pt.mleiria.bean.IClientBean;
import pt.mleiria.bean.ICryptoBean;

/**
 * @author NB13712
 * 
 */

public class ImkServlet extends HttpServlet {
	
	@EJB
	private IClientBean clientBean;
	@EJB
	private ICryptoBean cryptoBean;
	
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		
		try {
			final int op = Integer.parseInt(request.getParameter("op"));
			final String name = request.getParameter("name");
			int key_id;
			switch (op){
				case Constants.insertMasterKey: 
					clientBean.insertMasterKey(name);
					out.println("Created and persisted...");
					break;
				case Constants.encryptText:
					final String plainText = request.getParameter("text");
					key_id = Integer.parseInt(request.getParameter("key"));
					final String encryptedText = cryptoBean.encryptText(name, key_id, plainText);
					out.println(encryptedText);
					break;
				case Constants.decryptText:
					final String cipherText = request.getParameter("text");
					key_id = Integer.parseInt(request.getParameter("key"));
					final String decryptedText = cryptoBean.decryptText(name, key_id, cipherText);
					out.println(decryptedText);
			}
			
		} catch (Exception e) {
			out.println(e.getMessage());
			e.printStackTrace();
		}
		

	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
